<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Canvas移动小球示例</title>
    <style>
        body {
            margin: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            background-color: #f0f0f0;
        }
        canvas {
            border: 2px solid #333;
        }
    </style>
</head>
<body>
    <canvas id="gameCanvas" width="500" height="400"></canvas>

    <script>
        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');
        
        // 小球属性
        const ball = {
            x: canvas.width / 2,
            y: canvas.height / 2,
            radius: 20,
            speed: 5,
            dx: 0,
            dy: 0
        };
        
        // 键盘状态
        const keys = {
            ArrowUp: false,
            ArrowDown: false,
            ArrowLeft: false,
            ArrowRight: false
        };
        
        // 监听键盘事件
        document.addEventListener('keydown', (e) => {
            if (keys.hasOwnProperty(e.key)) {
                keys[e.key] = true;
            }
        });
        
        document.addEventListener('keyup', (e) => {
            if (keys.hasOwnProperty(e.key)) {
                keys[e.key] = false;
            }
        });
        
        // 更新小球位置
        function update() {
            // 根据按键设置速度
            ball.dx = 0;
            ball.dy = 0;
            
            if (keys.ArrowUp) ball.dy = -ball.speed;
            if (keys.ArrowDown) ball.dy = ball.speed;
            if (keys.ArrowLeft) ball.dx = -ball.speed;
            if (keys.ArrowRight) ball.dx = ball.speed;
            
            // 更新位置
            ball.x += ball.dx;
            ball.y += ball.dy;
            
            // 边界检测
            if (ball.x - ball.radius < 0) ball.x = ball.radius;
            if (ball.x + ball.radius > canvas.width) ball.x = canvas.width - ball.radius;
            if (ball.y - ball.radius < 0) ball.y = ball.radius;
            if (ball.y + ball.radius > canvas.height) ball.y = canvas.height - ball.radius;
        }
        
        // 绘制场景
        function draw() {
            // 清空画布
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            
            // 绘制小球
            ctx.beginPath();
            ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2);
            ctx.fillStyle = '#3498db';
            ctx.fill();
            ctx.lineWidth = 3;
            ctx.strokeStyle = '#2980b9';
            ctx.stroke();
        }
        
        // 游戏循环
        function gameLoop() {
            update();
            draw();
            requestAnimationFrame(gameLoop);
        }
        
        // 启动游戏
        gameLoop();
    </script>
</body>
</html>
